import * as winston from 'winston'
import * as DailyRotateFile from 'winston-daily-rotate-file'

const { combine, timestamp, label, printf } = winston.format

const infoFormat = printf(({ level, message, timestamp }) => {
  return `${timestamp} ${level}: ${message}`
})

const errFormat = printf(({ level, message, label, timestamp }) => {
  return `${timestamp} [${label}] ${level}: ${message}`
})

const consoleFormat = printf(({ level, service, message, label, timestamp }) => {
  return `[${label}] ${timestamp} [${service}] ${level}: ${message}`
})

// 日志设置
// const levels = {
//   error: 0,
//   warn: 1,
//   info: 2,
//   http: 3,
//   verbose: 4,
//   debug: 5,
//   silly: 6,
// };

export const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  defaultMeta: { service: 'app-service' },
  transports: [
    new winston.transports.Console({
      level: 'error',
      format: combine(label({ label: 'Winston' }), timestamp(), consoleFormat),
    }), // 是否输出到控制台
    new DailyRotateFile({
      filename: './log/error-%DATE%.log',
      level: 'error',
      format: combine(label({ label: '错误!' }), timestamp(), errFormat),
      // datePattern: 'YYYY-MM-DD-HH', // 按小时分割
      zippedArchive: true,
      maxSize: '1m',
      maxFiles: '1d',
    }),
    new DailyRotateFile({
      filename: './log/combined-%DATE%.log',
      format: combine(timestamp(), infoFormat),
      zippedArchive: true,
      maxSize: '1m',
      maxFiles: '1d',
    }),
  ],
})
